"use strict";
/**
 * 根据公司编码，下载公司所有的公告信息
 */

const url = require('url');
const querystring = require('querystring');
const utility = require('./utility');
const request = require('request');
const path = require('path');
const fs = require('fs');
const config = require('./config');
const util = require('util');

/**
 * 获取公司公告信息列表的Url
 */
var getCompanyNoticeReqUrl = (companyCode, pageIndex) => {
    return url.format({
        protocol: 'http',
        host: 'www.neeq.com.cn',
        pathname: '/disclosureInfoController/infoResult.do',
        search: querystring.stringify({
            callback: 'callFun',
            page: pageIndex,
            disclosureType: 5,
            companyCd: companyCode,
            isNewThree: 1,
            startTime: '',
            endTime: '',
            keyword: '',
            xxfcbj: '',
            t: new Date().getTime()
        })
    });
};

/**
 * 构造下载文档的url
 */
var getCompanyNoticeDocUrl = filePath => {
    return url.format({
        protocol: 'http',
        host: 'www.neeq.com.cn',
        pathname: filePath,
        t: new Date().getTime()
    });
};

/**
 * 根据公司的公告信息列表，下载公告文档

             * listinfo{
             *  content:[
             *      companyCd:"831715"
                    companyName:"瀚特信息"
                    destFilePath:"/disclosure/2016/2016-08-31/1472638708_891654.pdf"
                    disclosureCode:"97f8e58456de51920156e01a7d122bea"
                    disclosurePostTitle:""
                    disclosureSubType:""
                    disclosureTitle:"[临时公告]瀚特信息:第二届董事会第十次会议决议公告"
                    disclosureType:"9504"
                    disclosureYear:0
                    dKey:""
                    fileExt:"pdf"
                    filePath:""
                    isEmergency:1
                    isNewThree:1
                    publishDate:"2016-08-31"
                    publishOrg:"9601-1003"
                    state:1
                    upDate:Object
                    xxfcbj:"0"
             *  ],
             *  firstPage:true,         //是否是第一页
             *  lastPage:false,         //是否是最后一页
             *  number:0,               //第几个分页
             *  numberOfElements:20,    //当前分页的数量
             *  size:20,                //分页大小
             *  sort:null,              //排序
             *  totalElements:54,       //总数
             *  totalPages:3            //分页数
             * }
             *              
*/
var downloadNoteDoc = listInfo => {
    if (listInfo.totalElements < 1) {
        console.error("没有数据");
        return;
    }
    let orderPre = listInfo.number * listInfo.size;
    for (let i = 0; i < listInfo.content.length; i++) {
        let noticeObjItem = listInfo.content[i];
        let companyName = noticeObjItem.companyName;
        let destFilePath = noticeObjItem.destFilePath;
        let destFileName = noticeObjItem.disclosureTitle;
        let destFileExt = noticeObjItem.fileExt;
        let publishDate = noticeObjItem.publishDate;
        let companyCd = noticeObjItem.companyCd;
        let order = orderPre + i;
        let orderStr = "[" + order + "] ";
        //目录
        let localDir = path.join(config.basePath, companyCd + "_" + companyName);
        //如果目录不存在，就创建
        if (!fs.existsSync(localDir)) {
            fs.mkdirSync(localDir);
        }
        //构造文件路径
        let fileName = utility.getFileName(util.format("%s_%d_%s", publishDate, order, destFileName), destFileExt);
        let localFilePath = path.join(localDir, fileName);
        //fs.openSync(localFilePath,'w');
        //下载文件
        console.log(orderStr + "准备下载 " + fileName);
        //构造写流
        let writeStream = fs.createWriteStream(localFilePath);
        writeStream.on('finish', () => {
            //console.log(util.format("%s 下载完成 %s", orderStr, localFilePath));
        }).on('error', err => {
            //console.log(util.format("%s %s 下载出错: %s", orderStr, localFilePath, err));
        });
        request.get(getCompanyNoticeDocUrl(destFilePath), { timeout: 1000 * 60 })
            .on('response', res => {
                //console.log(orderStr + "响应 " + res.statusCode + " " + fileName);
            })
            .on('error', err => {
                //console.log(orderStr + "下载 " + fileName + " 出错，错误信息：" + err);
            })
            .pipe(writeStream);
    }
};

/**
 * 获取公司的公告信息列表
 */
var getNoteInfo = (companyCode, pageIndex) => {
    pageIndex = pageIndex ? pageIndex : 0; //默认是0
    console.log(util.format("分页%d", pageIndex));
    let url = getCompanyNoticeReqUrl(companyCode, pageIndex);
    //发请求获取
    console.log(url);
    request.get(url, { timeout: 1000 * 60 }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
            let noteObj = utility.parseResponseBody(body);
            let listInfo = noteObj.listInfo;
            /**
             * listinfo{
             *  content:[
             *      companyCd:"831715"
                    companyName:"瀚特信息"
                    destFilePath:"/disclosure/2016/2016-08-31/1472638708_891654.pdf"
                    disclosureCode:"97f8e58456de51920156e01a7d122bea"
                    disclosurePostTitle:""
                    disclosureSubType:""
                    disclosureTitle:"[临时公告]瀚特信息:第二届董事会第十次会议决议公告"
                    disclosureType:"9504"
                    disclosureYear:0
                    dKey:""
                    fileExt:"pdf"
                    filePath:""
                    isEmergency:1
                    isNewThree:1
                    publishDate:"2016-08-31"
                    publishOrg:"9601-1003"
                    state:1
                    upDate:Object
                    xxfcbj:"0"
             *  ],
             *  firstPage:true,         //是否是第一页
             *  lastPage:false,         //是否是最后一页
             *  number:0,               //第几个分页
             *  numberOfElements:20,    //当前分页的数量
             *  size:20,                //分页大小
             *  sort:null,              //排序
             *  totalElements:54        //总数
             *  totalPages:3            //分页数
             * }
             * 
             * 
             * 
             */

            //如果是第一个分页
            if (listInfo.firstPage && listInfo.content.length > 0) {
                let companyCode = listInfo.content[0].companyCd;
                let companyName = listInfo.content[0].companyName;
                console.log(util.format("[%d %s] 总共有 %d 条数据, %d 个分页。", companyCode, companyName, listInfo.totalElements, listInfo.totalPages));
            }

            //下载PDF文档
            downloadNoteDoc(listInfo);
            //页数加一
            pageIndex++;
            if (pageIndex < listInfo.totalPages) {
                //继续请求公告列表
                getNoteInfo(companyCode, pageIndex);
            }

        } else {
            console.log(util.format("获取分页%d出错，错误信息：%s", pageIndex, error));
        }
    }).on('error', err => {
        console.log(util.format("获取分页%d出错，错误信息：%s", pageIndex, err));
    });
};

/**
 * 转入公司编码，下载公司的所有公告
 */
module.exports.downloadNoticeDoc = getNoteInfo;